package org.jeecg.modules.zixishi.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.meituan.sdk.DefaultMeituanClient;
import com.meituan.sdk.MeituanClient;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.auth.MeituanTokenData;
import com.meituan.sdk.auth.MeituanTokenResponse;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.RshopDeal;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.TuangouDealQueryshopdealRequest;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.TuangouDealQueryshopdealResponse;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptConsume.TuangouReceiptConsumeRequest;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptConsume.TuangouReceiptConsumeResponse;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptPrepare.TuangouReceiptPrepareRequest;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptPrepare.TuangouReceiptPrepareResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.coupon.entity.Coupon;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.service.ICouponService;
import org.jeecg.modules.coupon.service.IMyCouponService;
import org.jeecg.modules.discount.entity.Discount;
import org.jeecg.modules.discount.service.IDiscountService;
import org.jeecg.modules.goods.entity.Goods;
import org.jeecg.modules.goods.service.IGoodsService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.order.service.IOrderService;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.entity.ThirdToken;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecg.modules.zixishi.service.*;
import org.jeecg.modules.zixishi.vo.ZixishiPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @Author: jeecg-boot
* @Date:   2024-05-19
* @Version: V1.0
*/
@RestController
@RequestMapping("/meituan")
@Slf4j
public class MeituanController {

    @Autowired
    private MeituanClient meituanClient;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IMyCouponService myCouponService;
    @Autowired
    private IThirdTokenService thirdTokenService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/scope")
    public Map scope(HttpServletRequest request) throws Exception{

        try {
            MeituanTokenResponse response = meituanClient.getOAuthToken(58,request.getParameter("code"));
            if(response.isSuccess()){
                MeituanTokenData tokenData = response.getData();
                redisUtil.set("meituantoken",tokenData.getAccessToken());

                ThirdToken thirdToken = new ThirdToken();
                thirdToken.setAccessToken(tokenData.getAccessToken())
                        .setRefreshToken(tokenData.getRefreshToken())
                        .setThirdType("meituan");
                thirdTokenService.save(thirdToken);

                Map retMap = new HashMap(){{
                    put("data", "sucess");
                }};
                return retMap;
            }else{
                throw new Exception(response.getMsg());
            }

        } catch (MtSdkException e) {
            throw new Exception(e);
        }
    }

    @GetMapping(value = "/queryshopdeal")
    public Result<List> queryShopDeal() {
        try {
            TuangouDealQueryshopdealRequest request = new TuangouDealQueryshopdealRequest();

            request.setOffset(1);
            request.setLimit(100);
            request.setSource(1);

            MeituanResponse<TuangouDealQueryshopdealResponse> response = meituanClient.invokeApi(request, "" + redisUtil.get("meituantoken"));
            if (response.isSuccess()) {
                List<RshopDeal> list = response.getData().getResult();
                if(CollectionUtil.isNotEmpty(list)){
                    RshopDeal deal = new RshopDeal();
                    deal.setDealId(0l);
                    deal.setTitle("解除关联");
                    list.add(0, deal);
                }
                return Result.OK(list);
            }
            return Result.error("查询美团出错" + response.getMsg());
        }catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    @PostMapping("/consume")
    public Result consume(@RequestBody Map map ) {
        String receiptCode = map.get("receiptCode").toString();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            TuangouReceiptPrepareRequest tuangouReceiptPrepareRequest = new TuangouReceiptPrepareRequest();
            tuangouReceiptPrepareRequest.setReceiptCode(receiptCode);
            MeituanResponse<TuangouReceiptPrepareResponse> response = meituanClient.invokeApi(tuangouReceiptPrepareRequest, "" + redisUtil.get("meituantoken"));
            if(response.isSuccess()) {
                Long dealId = response.getData().getDealId();
                List<Coupon> couponList = couponService.list(new LambdaQueryWrapper<Coupon>()
                        .eq(Coupon::getDealId, dealId)
                        .eq(Coupon::getStatus, 1)
                        .orderByAsc(Coupon::getIsort)
                );
                if(null == couponList || couponList.size() == 0) {
                    return Result.error("对应的商家卡券不存在，请联系商家");
                }
                MyCoupon myCoupon = myCouponService.createMyCouponfromMeituan(sysUser, couponList.get(0),response.getData());
                return Result.ok(myCoupon);
            }else{
                return Result.error(response.getMsg());
            }
        }catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

//    public static void main(String[] args) throws Exception{
////        String refreshToken = "f355240df49b8a2b06481a1d2193b0997087998f597a636545dcdddf604776ccfc53fb3367e358debb12c97d759d9270ea51cef7a1666887725fc9a4a3b1b8e091831ee23d9911723a669876002e82a991a70d360f4d5e9a7e0a35c9af53733e";
////        MeituanTokenResponse tokenResponse = meituanClient.refreshToken(58,refreshToken);
////        System.out.println(tokenResponse);
//
//        TuangouReceiptPrepareRequest tuangouReceiptPrepareRequest = new TuangouReceiptPrepareRequest();
//
//        String testcode = "8786718633";
//        String zxscode = "6875075309";
//        tuangouReceiptPrepareRequest.setReceiptCode(zxscode);
//
//        MeituanResponse<TuangouReceiptPrepareResponse> response = meituanClient.invokeApi(tuangouReceiptPrepareRequest, token);
//
//        System.out.println(response);
//
//        TuangouDealQueryshopdealRequest tuangouDealQueryshopdealRequest = new TuangouDealQueryshopdealRequest();
//
//        tuangouDealQueryshopdealRequest.setOffset(1);
//        tuangouDealQueryshopdealRequest.setLimit(100);
//        tuangouDealQueryshopdealRequest.setSource(1);
//
//        MeituanResponse<TuangouDealQueryshopdealResponse> response2 = meituanClient.invokeApi(tuangouDealQueryshopdealRequest, token);
//
//        System.out.println(response2);
//
//    }
}
